package com.netty.java.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @Author: TongRui乀
 * @Date: 2020/1/12 10:17
 * @description：
 */
@Slf4j
public class NioClient {


    public static void main(String[] args) throws Exception {

        startNioClient(8888, "hello");

    }


    public static void startNioClient(int port, String message) throws IOException {

        // 初始化channel
        SocketChannel socketChannel = SocketChannel.open();
        // 设置非阻塞
        socketChannel.configureBlocking(false);
        // 定义server地址
        InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
        // 连接服务端
        if (!socketChannel.connect(inetSocketAddress)) {
            if (!socketChannel.finishConnect()) {
                log.info("等待连接Server端");
            }
        }
        // 定义buffer
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
        // 发送数据
        socketChannel.write(buffer);

        log.info("发送数据完成");


        ByteBuffer readBuffer = ByteBuffer.allocate(1024);

        int read = socketChannel.read(readBuffer);

        readBuffer.flip();

        byte[] bytes = new byte[readBuffer.remaining()];

        readBuffer.get(bytes);

        log.info("receive message from server :{}", new String(bytes));


    }

}
